/*
	箭头图形
*/
define(
	[
		'require',
		'zrender/tool/util',
		'zrender/tool/area'
	],
	function(require) {
		"use strict";

		var BaseShape = require('zrender/shape/Base');
		var zrUtil = require('zrender/tool/util');

		/*
			箭头图形
		*/
		function Arrow(options) {
			this.brushTypeOnly = "both";
			BaseShape.call(this, options);
		}
		Arrow.prototype = {
			type: 'arrow',
			/**
			   创建线条路径
			   @param {CanvasRenderingContext2D} ctx
			   @param {module:zrender/shape/Line~ILineStyle} style
			 */
			buildPath: function(ctx, style) {
				var xStart = style.xStart,
					yStart = style.yStart,
					xEnd = style.xEnd,
					yEnd = style.yEnd;

				var arrow = [
					[2, 0],
					[-10, -4],
					[-7, 0],
					[-10, 4]
				];

				ctx.fillStyle = style.color;
				ctx.strokeStyle = style.strokeColor;

				function drawFilledPolygon(shape) {
					ctx.moveTo(shape[0][0], shape[0][1]);

					for (var p in shape) {
						if (p > 0) ctx.lineTo(shape[p][0], shape[p][1]);
					}

					ctx.lineTo(shape[0][0], shape[0][1]);
					//ctx.fill();
				};

				function translateShape(shape, x, y) {
					var rv = [];
					for (var p in shape) {
						rv.push([shape[p][0] + x, shape[p][1] + y]);
					}
					return rv;
				}

				function rotateShape(shape, ang) {
					var rv = [];
					for (var p in shape) {
						rv.push(rotatePoint(ang, shape[p][0], shape[p][1]));
					}
					return rv;
				}

				function rotatePoint(ang, x, y) {
					return [
						(x * Math.cos(ang)) - (y * Math.sin(ang)),
						(x * Math.sin(ang)) + (y * Math.cos(ang))
					];
				}

				function drawLineArrow(x1, y1, x2, y2) {
					ctx.moveTo(x1, y1);
					ctx.lineTo(x2, y2);
					//ctx.stroke();
					var ang = Math.atan2(y2 - y1, x2 - x1);
					drawFilledPolygon(translateShape(rotateShape(arrow, ang), x2, y2));
				}

				drawLineArrow(xStart, yStart, xEnd, yEnd);
				return;
			},

			/**
			   计算返回线条的包围盒矩形
			   @param {module:zrender/shape/Line~ILineStyle} style
			   @return {module:zrender/shape/Base~IBoundingRect}
			 */
			getRect: function(style) {
				if (style.__rect) {
					return style.__rect;
				}

				var lineWidth = style.lineWidth || 1;
				style.__rect = {
					x: Math.min(style.xStart, style.xEnd) - lineWidth,
					y: Math.min(style.yStart, style.yEnd) - lineWidth,
					width: Math.abs(style.xStart - style.xEnd) + lineWidth,
					height: Math.abs(style.yStart - style.yEnd) + lineWidth
				};

				return style.__rect;
			},

			isCover: function(x, y) {
				var originPos = this.transformCoordToLocal(x, y);
				x = originPos[0];
				y = originPos[1];

				// 快速预判并保留判断矩形
				if (this.isCoverRect(x, y)) {
					var area = this.style;
					// 矩形内
					return require('zrender/tool/area').isInsideLine(
						area.xStart, area.yStart,
						area.xEnd, area.yEnd,
						area.lineWidth + 15, x, y
					);
				}

				return false;
			},

			getHighlightZoom: function() {
				return 3;
			}
		};
		zrUtil.inherits(Arrow, BaseShape);

		return Arrow;
	}
);